<template>
  <div class="template-file-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>模板文件管理</h1>
        <p>管理系统模板文件，支持在线编辑、预览、备份等功能</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          新建模板
        </el-button>
        <el-button @click="refreshFileList">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="类型">
          <el-select v-model="searchForm.category" placeholder="选择类型" clearable style="width: 150px">
            <el-option 
              v-for="theme in templateCategoryOptions" 
              :key="theme.label" 
              :label="theme.label" 
              :value="theme.category" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件类型">
          <el-select v-model="searchForm.type" placeholder="选择类型" clearable style="width: 120px">
            <el-option 
              v-for="type in supportedTypes" 
              :key="type" 
              :label="type.toUpperCase()" 
              :value="type" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="搜索文件名" 
            style="width: 200px"
            @keyup.enter="searchFiles"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchFiles">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 文件列表 -->
    <div class="file-list-section">
      <div class="list-toolbar">
        <div class="toolbar-left">
          <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
          <el-button 
            type="danger" 
            size="small" 
            :disabled="selectedFiles.length === 0"
            @click="batchDelete"
          >
            批量删除
          </el-button>
          <el-button 
            size="small" 
            :disabled="selectedFiles.length === 0"
            @click="batchBackup"
          >
            批量备份
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-button-group>
            <el-button 
              :type="viewMode === 'list' ? 'primary' : ''" 
              size="small"
              @click="viewMode = 'list'"
            >
              <el-icon><List /></el-icon>
            </el-button>
            <el-button 
              :type="viewMode === 'grid' ? 'primary' : ''" 
              size="small"
              @click="viewMode = 'grid'"
            >
              <el-icon><Grid /></el-icon>
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 列表视图 -->
      <el-table 
        v-if="viewMode === 'list'"
        :data="filteredFiles" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="文件名" prop="name" min-width="200">
          <template #default="{ row }">
            <div class="file-name">
              <el-icon class="file-icon">
                <Document />
              </el-icon>
              <span>{{ row?.name || '未知文件' }}</span>
              <el-tag v-if="row?.type" size="small" class="file-type-tag">
                {{ row.type.toUpperCase() }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="类型" prop="category" width="120" >
          <template #default="{ row }">
            <span v-if="row.category === 1">文章</span>
            <span v-else-if="row.category === 2">栏目</span>
            <span v-else-if="row.category === 3">站点</span>
            <span v-else-if="row.category === 4">主题</span>
            <span v-else>{{ row.category }}</span>
          </template>
        </el-table-column>
        <el-table-column label="大小" prop="size" width="100">
          <template #default="{ row }">
            {{ formatFileSize(row?.size || 0) }}
          </template>
        </el-table-column>
        <el-table-column label="修改时间" prop="lastModified" width="160" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.exists ? 'success' : 'danger'" size="small">
              {{ row.exists ? '存在' : '不存在' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editFile(row)">编辑</el-button>
            <el-dropdown @command="handleFileAction">
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{action: 'preview', file: row}">预览</el-dropdown-item>
                  <el-dropdown-item :command="{action: 'copy', file: row}">复制</el-dropdown-item>
                  <el-dropdown-item :command="{action: 'rename', file: row}">重命名</el-dropdown-item>
                  <el-dropdown-item :command="{action: 'backup', file: row}">备份</el-dropdown-item>
                  <el-dropdown-item :command="{action: 'history', file: row}">历史</el-dropdown-item>
                  <el-dropdown-item :command="{action: 'download', file: row}">下载</el-dropdown-item>
                  <el-dropdown-item :command="{action: 'delete', file: row}" divided>删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 网格视图 -->
      <div v-else class="file-grid">
        <div
          v-for="file in filteredFiles"
          :key="file?.path || file?.name || Math.random()"
          class="file-card"
          :class="{ selected: file?.path && selectedFiles.includes(file.path) }"
          @click="file?.path && toggleFileSelection(file.path)"
        >
          <div class="file-card-header">
            <el-icon class="file-icon">
              <Document />
            </el-icon>
            <el-checkbox 
              :model-value="selectedFiles.includes(file.path)"
              @change="toggleFileSelection(file.path)"
              @click.stop
            />
          </div>
          <div class="file-card-body">
            <div class="file-name" :title="file?.name || ''">{{ file?.name || '未知文件' }}</div>
            <div class="file-meta">
              <span class="file-theme">{{ file?.theme || '未知主题' }}</span>
              <span class="file-size">{{ formatFileSize(file?.size || 0) }}</span>
            </div>
          </div>
          <div class="file-card-actions">
            <el-button size="small" @click.stop="file && editFile(file)">编辑</el-button>
            <el-button size="small" @click.stop="file && previewFile(file)">预览</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialog.visible"
      :title="editDialog.title"
      width="90%"
      :before-close="handleEditDialogClose"
      top="5vh"
    >
      <div class="editor-container">
        <div class="editor-toolbar">
          <el-button type="primary" @click="saveFile">保存</el-button>
          <el-button @click="validateFile">验证语法</el-button>
          <el-button @click="previewCurrentFile">预览</el-button>
          <el-button @click="formatCode">格式化</el-button>
        </div>
        <div class="editor-content">
          <textarea 
            ref="codeEditor"
            v-model="editDialog.content"
            class="code-editor"
          ></textarea>
        </div>
      </div>
    </el-dialog>

    <!-- 创建文件对话框 -->
    <el-dialog v-model="createDialog.visible" title="创建模板文件" width="500px">
      <el-form :model="createForm" :rules="createRules" ref="createFormRef" label-width="80px">
        <el-form-item label="类型" prop="category">
          <el-select v-model="createForm.category" placeholder="选择类型" style="width: 100%">
            <el-option
              v-for="option in templateCategoryOptions"
              :key="option.label"
              :label="option.label"
              :value="option.category"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据模型" prop="dataModelName"> 
          <el-select v-model ="createForm.dataModelName" placeholder="选择数据模型" style="width: 100%">
            <el-option
              v-for="model in modelOptions"
              :key="model.name"
              :label="model.name"
              :value="model.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件名" prop="templateName">
          <el-input v-model="createForm.templateName" placeholder="输入文件名" />
        </el-form-item>
        <el-form-item label="文件类型" prop="type">
          <el-select v-model="createForm.type" placeholder="选择类型" style="width: 100%">
            <el-option 
              v-for="type in supportedTypes" 
              :key="type" 
              :label="type.toUpperCase()" 
              :value="type" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="初始内容">
          <el-input 
            v-model="createForm.content" 
            type="textarea" 
            :rows="6"
            placeholder="输入初始模板内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="createFile">创建</el-button>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewDialog.visible" title="模板预览" width="80%">
      <div class="preview-container">
        <div class="preview-toolbar">
          <el-button @click="refreshPreview">刷新预览</el-button>
        </div>
        <div class="preview-content" v-html="previewDialog.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { modelApi } from '@/api/model'
import * as templateFileApi from '@/api/template-file'
import { ArrowDown, Document, Grid, List, Plus, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, nextTick, onErrorCaptured, onMounted, reactive, ref } from 'vue'

// 响应式数据
const loading = ref(false)
const viewMode = ref('list')
const selectAll = ref(false)
const selectedFiles = ref([])
const files = ref([])
const themes = ref([])
const supportedTypes = ref([])
const modelOptions = ref([])
const isModelLoading=ref(false)
//模版分类的选项（1.文章2.栏目3.站点）
const templateCategoryOptions=[
  { label: '文章', value: 'article' ,category:1},
  { label: '栏目', value: 'column' ,category:2},
  { label: '站点', value: 'site' ,category:3},
  {label:'主题',value:'theme',category:4}
]
// 搜索表单
const searchForm = reactive({
  category: '',
  type: '',
  keyword: ''
})

// 编辑对话框
const editDialog = reactive({
  visible: false,
  title: '',
  content: '',
  file: null
})

// 创建对话框
const createDialog = reactive({
  visible: false
})

const createForm = reactive({
  category: '',
  dataModelName:'',
  templateName: '',
  type: 'ftl',
  content: '',
})

const createRules = {
  category: [{ required: true, message: '请选择模版类型', trigger: 'change' }],
  dataModelName:[{required: true, message: '请选择数据模型', trigger: 'change'}],
  templateName: [{ required: true, message: '请输入文件名', trigger: 'blur' }],
  type: [{ required: true, message: '请选择文件类型', trigger: 'change' }]
}

// 预览对话框
const previewDialog = reactive({
  visible: false,
  content: ''
})

// 计算属性
const filteredFiles = computed(() => {
  // 首先过滤掉null/undefined的文件
  let result = (files.value || []).filter(file => file && typeof file === 'object')

  if (searchForm.category) {
    console.log(searchForm.category)
    result = result.filter(file => file.category === searchForm.category)
  }

  if (searchForm.type) {
    result = result.filter(file => file.type === searchForm.type)
  }

  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase()
    result = result.filter(file =>
      (file.name && file.name.toLowerCase().includes(keyword)) ||
      (file.path && file.path.toLowerCase().includes(keyword))
    )
  }

  return result
})

//监听器
watch(()=>createForm.category,(newCategory)=>{
  if(newCategory){
    console.log(newCategory)
    loadModelOptions(newCategory)
  }
},{immediate:true})

// 方法
const loadFiles = async () => {
  loading.value = true
  try {
    const response = await templateFileApi.getAllTemplateFiles()
    // 确保数据是数组，并过滤掉null/undefined值
    const rawData = response.data || []
    files.value = Array.isArray(rawData) ? rawData.filter(file => file && typeof file === 'object') : []
  } catch (error) {
    console.error('加载模板文件失败:', error)
    ElMessage.error('加载模板文件失败')
    files.value = [] // 确保出错时也有一个空数组
  } finally {
    loading.value = false
  }
}
const loadModelOptions=async(newCategory)=>{
  createForm.dataModelName='';
  isModelLoading.value=true;
  try {
    const response = await modelApi.getModelsByType(newCategory)
    modelOptions.value = response.data || []
    console.log(modelOptions.value)
  } catch (error) {
    console.error('加载数据模型失败:', error)
    ElMessage.error('加载数据模型失败')
    modelOptions.value = [] // 确保出错时也有一个空数组
  } finally {
    isModelLoading.value=false;
  }

}
const loadSupportedTypes = async () => {
  try {
    const response = await templateFileApi.getSupportedTemplateTypes()
    supportedTypes.value = response.data || []
  } catch (error) {
    console.error('加载支持的模板类型失败', error)
  }
}

const loadThemes = async () => {
  try {
    // 使用专门的主题名称API
    const response = await templateFileApi.getThemeNames()
    if (response.code === 0) {
      themes.value = response.data || []
    } else {
      console.error('获取主题名称列表失败:', response.msg)
      // 如果API失败，从文件列表中提取主题作为备选方案
      const themeSet = new Set(files.value.map(file => file.theme).filter(theme => theme))
      themes.value = Array.from(themeSet)
    }
  } catch (error) {
    console.error('获取主题名称列表失败:', error)
    // 如果API失败，从文件列表中提取主题作为备选方案
    const themeSet = new Set(files.value.map(file => file.theme).filter(theme => theme))
    themes.value = Array.from(themeSet)
  }
}

const refreshFileList = async () => {
  // 先加载主题列表，再加载文件列表
  await loadThemes()
  await loadFiles()
}

const searchFiles = () => {
  // 搜索逻辑已在计算属性中实现
}

const resetSearch = () => {
  searchForm.category = ''
  searchForm.type = ''
  searchForm.keyword = ''
}

const handleSelectAll = (checked) => {
  if (checked) {
    selectedFiles.value = filteredFiles.value.map(file => file.path)
  } else {
    selectedFiles.value = []
  }
}

const handleSelectionChange = (selection) => {
  selectedFiles.value = selection.map(file => file.path)
  selectAll.value = selectedFiles.value.length === filteredFiles.value.length
}

const toggleFileSelection = (filePath) => {
  const index = selectedFiles.value.indexOf(filePath)
  if (index > -1) {
    selectedFiles.value.splice(index, 1)
  } else {
    selectedFiles.value.push(filePath)
  }
  selectAll.value = selectedFiles.value.length === filteredFiles.value.length
}

const editFile = async (file) => {
  try {
    const response = await templateFileApi.getTemplateFileContent(file.theme, file.name)
    editDialog.file = file
    editDialog.title = `编辑模板文件 - ${file.name}`
    editDialog.content = response.data || ''
    editDialog.visible = true
    
    // 初始化代码编辑器
    nextTick(() => {
      initCodeEditor()
    })
  } catch (error) {
    ElMessage.error('加载文件内容失败')
  }
}

const saveFile = async () => {
  if (!editDialog.file) return
  
  try {
    await templateFileApi.saveTemplateFileContent(
      editDialog.file.theme, 
      editDialog.file.name, 
      editDialog.content
    )
    ElMessage.success('保存成功')
    editDialog.visible = false
    refreshFileList()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const validateFile = async () => {
  if (!editDialog.file) return
  
  try {
    const response = await templateFileApi.validateTemplateFile(
      editDialog.file.theme, 
      editDialog.file.name
    )
    
    if (response.data.valid) {
      ElMessage.success('模板语法正确')
    } else {
      ElMessage.error(`语法错误: ${response.data.error}`)
    }
  } catch (error) {
    ElMessage.error('验证失败')
  }
}

const previewFile = async (file) => {
  try {
    const response = await templateFileApi.previewTemplateFile(file.theme, file.name, {})
    previewDialog.content = response.data || ''
    previewDialog.visible = true
  } catch (error) {
    ElMessage.error('预览失败')
  }
}

const previewCurrentFile = () => {
  if (editDialog.file) {
    previewFile(editDialog.file)
  }
}

const formatCode = () => {
  // 简单的代码格式化
  try {
    // 这里可以集成更专业的代码格式化工具
    ElMessage.success('代码格式化完成')
  } catch (error) {
    ElMessage.error('格式化失败')
  }
}

const handleEditDialogClose = (done) => {
  ElMessageBox.confirm('确定要关闭编辑器吗？未保存的更改将丢失。')
    .then(() => {
      done()
    })
    .catch(() => {})
}

const showCreateDialog = () => {
  createForm.theme = ''
  createForm.templateName = ''
  createForm.type = 'ftl'
  createForm.content = ''
  createDialog.visible = true
}

const createFile = async () => {
  try {
    await templateFileApi.createTemplateFile(createForm)
    ElMessage.success('创建成功')
    createDialog.visible = false
    refreshFileList()
  } catch (error) {
    ElMessage.error('创建失败')
  }
}

const handleFileAction = async ({ action, file }) => {
  switch (action) {
    case 'preview':
      previewFile(file)
      break
    case 'copy':
      // TODO: 实现复制功能
      ElMessage.info('复制功能开发中')
      break
    case 'rename':
      // TODO: 实现重命名功能
      ElMessage.info('重命名功能开发中')
      break
    case 'backup':
      try {
        await templateFileApi.backupTemplateFile(file.theme, file.name)
        ElMessage.success('备份成功')
      } catch (error) {
        ElMessage.error('备份失败')
      }
      break
    case 'history':
      // TODO: 实现历史记录功能
      ElMessage.info('历史记录功能开发中')
      break
    case 'download':
      await downloadFile(file)
      break
    case 'delete':
      ElMessageBox.confirm(`确定要删除文件 ${file.name} 吗？`, '确认删除', {
        type: 'warning'
      }).then(async () => {
        try {
          await templateFileApi.deleteTemplateFile(file.theme, file.name)
          ElMessage.success('删除成功')
          refreshFileList()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      break
  }
}

const batchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedFiles.value.length} 个文件吗？`, '批量删除', {
    type: 'warning'
  }).then(async () => {
    try {
      await templateFileApi.batchOperateTemplateFiles({
        operation: 'delete',
        filePaths: selectedFiles.value,
        params: {}
      })
      ElMessage.success('批量删除成功')
      selectedFiles.value = []
      refreshFileList()
    } catch (error) {
      ElMessage.error('批量删除失败')
    }
  })
}

const batchBackup = async () => {
  try {
    await templateFileApi.batchOperateTemplateFiles({
      operation: 'backup',
      filePaths: selectedFiles.value,
      params: {}
    })
    ElMessage.success('批量备份成功')
  } catch (error) {
    ElMessage.error('批量备份失败')
  }
}

const formatFileSize = (size) => {
  // 类型检查和转换
  const numSize = Number(size)
  if (!numSize || isNaN(numSize) || numSize <= 0) return '-'

  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  let fileSize = numSize

  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }

  return `${fileSize.toFixed(1)} ${units[index]}`
}

const initCodeEditor = () => {
  // 这里可以集成 CodeMirror 或其他代码编辑器
  // 暂时使用简单的 textarea
}

const refreshPreview = () => {
  if (editDialog.file) {
    previewFile(editDialog.file)
  }
}

const downloadFile = async (file) => {
  try {
    const response = await templateFileApi.exportTemplateFile(file.theme, file.name)

    // 创建下载链接
    const blob = new Blob([response], { type: 'application/octet-stream' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = file.name
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('下载成功')
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败')
  }
}

// 生命周期
onMounted(async () => {
  try {
    // 先加载主题列表和支持的类型
    await Promise.all([
      loadThemes(),
      loadSupportedTypes()
    ])
    // 再加载文件列表
    await loadFiles()
  } catch (error) {
    console.error('模板文件管理页面初始化失败:', error)
    ElMessage.error('页面初始化失败')
  }
})

// 错误处理
onErrorCaptured((error, instance, info) => {
  console.error('模板文件管理页面捕获到错误:', error, info)
  ElMessage.error('页面渲染出现错误，请刷新重试')
  return false // 阻止错误继续传播
})
</script>

<style scoped lang="scss">
.template-file-management {
  padding: 24px;
  background: #f8f9fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .header-left {
    h1 {
      margin: 0 0 8px 0;
      font-size: 24px;
      color: #303133;
      font-weight: 600;
    }

    p {
      margin: 0;
      color: #606266;
      font-size: 14px;
    }
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }
}

.search-section {
  background: white;
  padding: 24px;
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .el-form {
    margin: 0;
  }

  .el-form-item {
    margin-bottom: 0;
    margin-right: 24px;

    &:last-child {
      margin-right: 0;
    }
  }
}

.file-list-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.list-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;

  .toolbar-left {
    display: flex;
    align-items: center;
    gap: 12px;
  }

  .toolbar-right {
    display: flex;
    align-items: center;
    gap: 12px;
  }
}

// 表格容器样式
.el-table {
  :deep(.el-table__body-wrapper) {
    max-height: 600px;
    overflow-y: auto;
  }
}

.file-name {
  display: flex;
  align-items: center;
  gap: 8px;

  .file-icon {
    color: #409eff;
  }

  .file-type-tag {
    margin-left: auto;
  }
}

.file-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
  padding: 24px;
  max-height: 600px;
  overflow-y: auto;
}

.file-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
  }
  
  &.selected {
    border-color: #409eff;
    background: #f0f9ff;
  }
}

.file-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  
  .file-icon {
    font-size: 24px;
    color: #409eff;
  }
}

.file-card-body {
  margin-bottom: 12px;
  
  .file-name {
    font-weight: 500;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .file-meta {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #909399;
  }
}

.file-card-actions {
  display: flex;
  gap: 8px;
}

.editor-container {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.editor-toolbar {
  padding: 12px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 12px;
}

.editor-content {
  flex: 1;
  
  .code-editor {
    width: 100%;
    height: 100%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 12px;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 14px;
    line-height: 1.5;
    resize: none;
    outline: none;
    
    &:focus {
      border-color: #409eff;
    }
  }
}

.preview-container {
  height: 600px;
  display: flex;
  flex-direction: column;
}

.preview-toolbar {
  padding: 12px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 12px;
}

.preview-content {
  flex: 1;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  overflow: auto;
  background: white;
}

// 编辑器样式
.editor-container {
  height: 70vh;
  display: flex;
  flex-direction: column;
}

.editor-toolbar {
  padding: 12px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 12px;
  display: flex;
  gap: 12px;
}

.editor-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.code-editor {
  flex: 1;
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 12px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  outline: none;

  &:focus {
    border-color: #409eff;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .template-file-management {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    padding: 16px;

    .header-actions {
      width: 100%;
      justify-content: flex-start;
    }
  }

  .search-section {
    padding: 16px;

    .el-form {
      flex-direction: column;

      .el-form-item {
        margin-right: 0;
        margin-bottom: 16px;
        width: 100%;

        .el-select,
        .el-input {
          width: 100% !important;
        }
      }
    }
  }

  .list-toolbar {
    flex-direction: column;
    gap: 12px;

    .toolbar-left,
    .toolbar-right {
      width: 100%;
      justify-content: flex-start;
    }
  }

  .file-grid {
    grid-template-columns: 1fr;
    padding: 16px;
  }

  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }

  .editor-container {
    height: 60vh;
  }
}
</style>
